package com.lagou.edu.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author: create by CharwayH
 * @description: com.lagou.edu.utils
 * @date:2022/3/6
 */
@Component
public class ConnectionUtils {

    // 存储当前线程的连接
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    @Autowired
    private DataSource dataSource;

    /**
     * 从当前线程获取连接
     */
    public Connection getCurrentConnection() throws SQLException {
        /**
         * 判断当前线程是否已经绑定连接，如果没有绑定则要从线程池中获取连接
         */
        Connection connection = threadLocal.get();
        if(connection == null){
            // 从连接池中获取连接
            connection = dataSource.getConnection();
            // 绑定到当前线程当中
            threadLocal.set(connection);
        }
        return connection;
    }
}